package com.example.zhihuijiaju;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

import static android.view.View.INVISIBLE;
import static android.view.View.inflate;


public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.RecyclerHolder>{
    private String TAG = "MyRVAdapter";
    private  List<Map<String, Object>> list;
    String Token;
    private Context context;
    private LayoutInflater layoutInflater;
    OnItemClickLitener mOnItemClickLitener;
    //新建点击事件接口
    public interface OnItemClickLitener {
        void onItemClick(int position);
    }
    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    public void IsClickLitener(int position) {
        mOnItemClickLitener.onItemClick(position);
    }



    public MyRVAdapter( Context context,List<Map<String, Object>> list,String ToKen){
        this.list = list;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
        this.Token = ToKen;
    }

    class RecyclerHolder extends RecyclerView.ViewHolder{
        TextView textView;
        CardView cardView;
        ProgressBar loading;
        ImageView open;
        ImageView stop;
        public RecyclerHolder(@NonNull View itemView) {
            super(itemView);
            this.textView = itemView.findViewById(R.id.deviceId);
            this.cardView = itemView.findViewById(R.id.Card);
            this.loading = itemView.findViewById(R.id.loading);
            this.open = itemView.findViewById(R.id.open);
            this.stop = itemView.findViewById(R.id.stop);
        }
    }

    @SuppressLint("ResourceType")
    @NonNull
    @Override
    public RecyclerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.devices_item, parent, false);
        RecyclerHolder recyclerHolder = new RecyclerHolder(view);
        return recyclerHolder;
    }

    /**
     * 绑定视图组件数据
     */
    @Override
    public void onBindViewHolder(@NonNull RecyclerHolder holder, int position) {
        Log.i("TAG", String.valueOf(position));
        holder.textView.setText((String) list.get(position).get("deviceId"));
        StatusCcheck(holder,position);

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //接口回调
//                IsClickLitener(position);
                CmdIssued(holder,position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return   list.size();
    }
    //查询状态
    private void StatusCcheck(RecyclerHolder holder, int position) {
        String deviceId = (String) list.get(position).get("deviceId");
        String CLIENT_ID = (String) list.get(position).get("CLIENT_ID");
        HttpLink httpLink = new HttpLink(Token,
                "https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/"+CLIENT_ID+"/devices/"+deviceId+"/shadow",
                "{}",
                Method.GET);

        httpLink.HttpListener(new HttpChangeListener() {
            @Override
            public void HttpChange(Response response)  {
                String body = "";
                try {
                    body = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG,body);

                JSONObject jsonObject = JSONObject.parseObject(body);

                try {
                    Log.i(TAG,jsonObject.getString("error_msg"));
                    Intent intent = new Intent();
                    intent.setClass(context, Login.class);
                    context.startActivity(intent);
                    return;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //Log.i(TAG,jsonObject.getString("shadow"));
                JSONArray jsonArray1 = jsonObject.getJSONArray("shadow");
                JSONObject jsonObject2 = jsonArray1.getJSONObject(0);
                //Log.i(TAG,jsonObject2.getString("reported"));
                jsonObject = JSONObject.parseObject(jsonObject2.getString("reported"));

                jsonObject2 = JSONObject.parseObject(jsonObject.getString("properties"));

                //  Log.i(TAG,jsonObject2.toString());

                int status = Integer.parseInt(jsonObject2.get("status").toString());

                //   Log.i(TAG, String.valueOf(status));
            //    GradientDrawable myGrad = (GradientDrawable)Switch1.getBackground();
                holder.loading.setVisibility(INVISIBLE);
                if(status==1){
                    //  sw_color( 0xe6e6e9f0, 0xe6ffecd2);
                  //  sw1_data = 0;
                    list.get(position).put("status",1);

                    holder.stop.post(new Runnable() {
                        @Override
                        public void run() {
                            holder.stop.setVisibility(View.VISIBLE);
                        }
                    });

                    Log.i(TAG,"已设置1");
                }
                else if (status==0){
                   // sw1_data = 1;
                    Log.i(TAG,"已设置0");
                    list.get(position).put("status",0);

                    holder.open.post(new Runnable() {
                        @Override
                        public void run() {
                            holder.open.setVisibility(View.VISIBLE);
                        }
                    });


                }
            }
        });
    }

    public  void CmdIssued(RecyclerHolder holder, int position)
    {
        //防止多次点击
//        if(Loading.getVisibility() == VISIBLE){
//            return;
//        }
        //   Vibrator vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);
        //     vibrator.vibrate(15);
        //显示加载动画
//        Loading.setVisibility(VISIBLE);
        holder.loading.setVisibility(View.VISIBLE);

        holder.open.post(new Runnable() {
            @Override
            public void run() {
                holder.open.setVisibility(View.INVISIBLE);
            }
        });
        holder.stop.post(new Runnable() {
            @Override
            public void run() {
                holder.stop.setVisibility(View.INVISIBLE);
            }
        });

        int cmd = (int) list.get(position).get("status");
        Log.i(TAG, String.valueOf(cmd));
        if(cmd ==1 ){cmd=0;list.get(position).put("status",0);}
        else if(cmd ==0){cmd=1;list.get(position).put("status",1);}
        else {return;}
        String deviceId = (String) list.get(position).get("deviceId");
        String CLIENT_ID = (String) list.get(position).get("CLIENT_ID");
        HttpLink httpLink = new HttpLink(Token,
                "https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/"+CLIENT_ID+"/devices/"+deviceId+"/commands",
                "{'service_id':'on_off','command_name':'on_off','paras': {'on_off':'"+cmd+"'}}",
                Method.POST);

        httpLink.HttpListener(new HttpChangeListener() {
            @Override
            public void HttpChange(Response response) {
                holder.loading.setVisibility(INVISIBLE);
                String body = "";
                try {
                    body = response.body().string();
                    Log.i(TAG,body);

                    int size = body.indexOf("error");

                    // Log.i(TAG, "color");
                    if(size==-1){
//                        if (sw1_data==0)
//                        {
//                            //  sw_color(0xe6ffecd2, 0xe6e6e9f0);
//
//                        }
//                        if(sw1_data==1)
//                        {
//                            //  sw_color( 0xe6e6e9f0, 0xe6ffecd2);
//                        }
//                        sw1_data++;
//                        if(sw1_data==2) {
//                            sw1_data=0;
//                        }
                        if(0 == (int)list.get(position).get("status")) {
                            holder.open.post(new Runnable() {
                                @Override
                                public void run() {
                                    holder.open.setVisibility(View.VISIBLE);
                                }
                            });

                        }
                        if (1==(int)list.get(position).get("status")){
                            holder.stop.post(new Runnable() {
                                @Override
                                public void run() {
                                    holder.stop.setVisibility(View.VISIBLE);
                                }
                            });
                        }
                    }
                    else{
                        Looper.prepare();
                        Toast.makeText(context,"设备未上线",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        Log.i(TAG,"设备未上线");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG,body);
            }
        });
    }

    //颜色动画
//    public void sw_color(int startColor,int endColor)
//    {
//        GradientDrawable myGrad = (GradientDrawable)Switch1.getBackground();
//        new Handler(Looper.getMainLooper()).post(new Runnable() {
//            @Override
//            public void run() {
//                ValueAnimator valueAnimator = ValueAnimator.ofArgb(startColor, endColor);
//                valueAnimator.setDuration(300);
//                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                    @Override
//                    public void onAnimationUpdate(ValueAnimator animation) {
//                        int color = (int) animation.getAnimatedValue();
//                        myGrad.setColor(color);
//                    }
//                });
//                valueAnimator.start();
//            }
//        });
//    }
}

